<template>
    <div class="specManager-container">
      <el-card >
        <!--    面包屑导航-->
        <div class="add">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>规格管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-button
          type="success"
          round
          @click="addGroup"
          size="mini"
          :loading="isAdding || isSearching">
          添加规格组
        </el-button>
        </div>
      </el-card>
      <el-card class="box-card" style="margin-top: 10px">
        <el-table
          :data="specGroupList"
          style="width: 100%;margin-top: 10px"
          @row-click="openColumn"
          @expand-change="expandSelect"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          v-loading ="isSearching"
        >
          <el-table-column
            type="expand" width="100px">
            <template slot-scope="scope">
              <el-tag
                v-for="(param, index) in scope.row.groupParam"
                :key="index"
                :disable-transitions="false"
                :closable="!isDeleting"
                @click="showTag(param)"
                @close="handleClose(param,scope.row.groupParam)">
                {{param.name}}
              </el-tag>
<!--              <el-input-->
<!--                class="input-new-tag"-->
<!--                v-if="inputVisible"-->
<!--                v-model="specParam.name"-->
<!--                ref="saveTagInput"-->
<!--                size="small"-->
<!--                :disabled="isAdding"-->
<!--                @keyup.enter.native="$event.target.blur"-->
<!--                @blur="handleInputConfirm(scope.$index,scope.row)"-->
<!--              >-->
<!--              -->
<!--              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>-->
                <!--      规格参数添加弹框-->
                <el-dialog
                  title= 添加规格参数
                  :visible.sync="isAddTag"
                  append-to-body
                  @close="closeForm"
                >
                  <el-form
                    :model="tagForm"
                    :rules="formRules"
                    ref="addTagForm"
                    label-width="170px"
                    :disabled="isAdding"
                  >
                    <el-form-item label="规格参数名称" prop="name">
                      <el-input :disabled="isAdding" v-model="tagForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="单位" prop="unit">
                      <el-input :disabled="isAdding" v-model="tagForm.unit"></el-input>
                    </el-form-item>
                    <el-form-item label="选项集(用逗号隔开,可选)" prop="options">
                      <el-input :disabled="isAdding" v-model="tagForm.options"></el-input>
                    </el-form-item>
                    <el-form-item label="是否是通用规格参数" prop="isGeneral">
<!--                      <div style="justify-content: center;display: flex;float:left;">-->
<!--                        <el-input type="radio" v-model.number="tagForm.isGeneral" value=1 style="width: 15px">-->
<!--                        <span style="margin-right: 20px">是</span>-->
<!--                        <el-input type="radio" v-model.number="tagForm.isGeneral" value=0 style="width: 15px">-->
<!--                        <span style="margin-right: 20px">否</span>-->
<!--                      </div>-->
                          <el-radio-group v-model="tagForm.isGeneral">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                          </el-radio-group>
                    </el-form-item>
<!--                    黑色,蓝色,混合色,白色,红色,绿色,渐变色,银色,金色,灰色,紫色,粉色,橙色,极光色,黄色,海蓝色,石墨色,其他-->
                    <el-form-item label="是否是可聚合规格参数" prop="isAggregation">
                          <el-radio-group v-model="tagForm.isAggregation">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                          </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否是sku聚合规格" prop="isSku">
                          <el-radio-group v-model="tagForm.isSku">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                          </el-radio-group>
                    </el-form-item>
                    <el-form-item label="规格类型" prop="type">
                      <el-select v-model="tagForm.type" placeholder="请选择">
                        <el-option
                          v-for="item in types"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="closeForm" :disabled="isAdding">取 消</el-button>
                    <el-button type="primary" @click="addTag(scope.row)" :loading="isAdding">确 定</el-button>
                  </div>
                </el-dialog>
              <el-dialog
                title= 编辑规格参数
                :visible.sync="isShowTag"
                append-to-body
                @close="closeForm"
              >
                <el-form
                  :model="newParam"
                  :rules="formRules"
                  ref="updateTagForm"
                  label-width="170px"
                  :disabled="isAdding"
                >
                  <el-form-item label="id">
                    <el-input disabled v-model="newParam.id"></el-input>
                  </el-form-item>
                  <el-form-item label="所属规格组">
                    <el-input disabled v-model="newParam.groupName"></el-input>
                  </el-form-item>
                  <el-form-item label="规格参数名称" prop="name">
                    <el-input :disabled="isAdding" v-model="newParam.name"></el-input>
                  </el-form-item>
                  <el-form-item label="单位" prop="unit">
                    <el-input :disabled="isAdding" v-model="newParam.unit"></el-input>
                  </el-form-item>
                  <el-form-item label="是否是通用规格参数" prop="isGeneral">
                    <el-radio-group v-model="newParam.isGeneral">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="是否是搜索可聚合规格" prop="isAggregation">
                    <el-radio-group v-model="newParam.isAggregation">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="是否是sku聚合规格" prop="isSku">
                    <el-radio-group v-model="newParam.isSku">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="选项集(用逗号隔开,可选)" prop="options">
                    <el-input :disabled="isAdding" v-model="newParam.options"></el-input>
                  </el-form-item>
                  <el-form-item label="规格类型" prop="type">
                    <el-select v-model="newParam.type" placeholder="请选择">
                      <el-option
                        v-for="item in types"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="closeForm" :disabled="isAdding">取 消</el-button>
                  <el-button type="primary" @click="updateTag(scope.row.groupParam)" :loading="isAdding">确 定</el-button>
                </div>
              </el-dialog>
              <el-button class="button-new-tag" size="small" @click="isAddTag = true">+ New</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="规格参数组名" width="1000px">
          </el-table-column>
          <el-table-column
            label="操作"
           width="100px">
            <!-- 如果需要自定义表格列模板，则把需要自定义的内容放到 template 里面 -->
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="删除参数组" placement="top-end">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  :loading="isDeleting"
                  @click="deleteSpecGroup(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!--    分页栏-->
      <el-pagination
        class="page"
        background
        layout="prev, pager, next"
        :current-page.sync = page
        :page-size.sync = size
        :disabled="isSearching"
        @current-change = pageChange
        :total="total">
      </el-pagination>
    </div>
</template>

<script>
import { getSpecGroup, deleteSpecGroupById, addSpecParam, deleteSpecParamById, addSpecGroup, updateSpecParamById } from '@/api/spec'
import { Message } from 'element-ui'
export default {
  name: 'SpecManager',
  components: {},
  props: {},
  data () {
    return {
      page: 1,
      size: 10,
      total: 0, // 总页数
      specGroupList: [], // 规格参数组列表
      specParamList: [], // 规格参数列表
      isSearching: false, // 搜索加载loading
      isAdding: false, // 添加loading
      isDeleting: false, // 删除loading
      isShowTag: false, // 标签详情弹框开关
      isAddTag: false, // 添加标签弹框开关
      inputVisible: false, // 增加规格组标签输入开关
      expands: [], // 展开行集合
      getRowKeys (row) { // 每行展开关键字
        return row.id
      },
      specParam: { // 规格参数对象（添加标签时使用）
        groupName: '', // 分组名
        categoryId: 0, // 对应分类id，这里时顶级参数，所以指定为0
        name: '' // 添加标签输入框内容
      },
      tag: {}, // 当前选中标签
      tagForm: {
        name: '', // 规格名
        groupName: '', // 对应规格组名
        options: '', // 可选项集
        categoryId: 0, // 所属分类id，顶级规格为0
        unit: '', // 单位
        isGeneral: '', // 是否是通用规格参数
        isAggregation: '', // 是否搜索可聚合
        isSku: '', // 是否是sku选择聚合规格
        type: '' // 规格类型
      },
      newParam: {
        id: 0, // ID
        name: '', // 规格名
        groupName: '', // 对应规格组名
        options: '', // 可选项集
        categoryId: 0, // 所属分类id，顶级规格为0
        unit: '', // 单位
        isGeneral: '', // 是否是通用规格参数
        isAggregation: '', // 是否搜索可聚合
        isSku: '', // 是否是sku选择聚合规格
        type: '' // 是否规格类型
      }, // 标签详情显示数据
      oldParam: {}, // 选中标签数据
      types: [
        {
          id: 0,
          name: '字符串'
        },
        {
          id: 1,
          name: '数值'
        },
        {
          id: 2,
          name: '日期(年)'
        },
        {
          id: 3,
          name: '日期(年月)'
        },
        {
          id: 4,
          name: '日期(年月日)'
        },
        {
          id: 5,
          name: '日期(年月日时分秒)'
        },
        {
          id: 6,
          name: '集合'
        }
      ], // 规格可选类型集合
      formRules: { // 表单验证规则
        name: [
          {
            required: true,
            message: '请输入规格参数名称',
            trigger: 'blur'
          },
          {
            max: 20,
            message: '长度最长是 20 个字符',
            trigger: 'blur'
          }
        ],
        unit: [
          {
            max: 10,
            message: '长度最长是 10 个字符',
            trigger: 'blur'
          }
        ],
        categoryId: [
          {
            required: true,
            message: '请输入所属分类ID',
            trigger: 'blur'
          },
          {
            pattern: /^[0-2147483648]$/, message: '超出输入范围', trigger: 'blur'
          }
        ],
        isGeneral: [
          { required: true, message: '请选择是否是通用规格', trigger: 'change' }
        ],
        isAggregation: [
          { required: true, message: '请选择是否是搜索可聚合规格', trigger: 'change' }
        ],
        isSku: [
          { required: true, message: '请选择是否是sku选择规格', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择规格类型', trigger: 'change' }
        ],
        options: [
          {
            max: 500,
            message: '长度最长是 500 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    this.getAllSpecGroup(this.page, this.size)
  },
  mounted () {
  },
  methods: {
    // -------------------------------------------------规格组-----------------------------------------------------------

    // 添加顶级规格组
    async addGroup () {
      this.isAdding = true
      await this.$prompt('规格组名', '添加', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\u4e00-\u9fffa-zA-Z]{1,15}$/,
        inputErrorMessage: '名称不能为空且不超过15个字'
      }).then(async ({ value }) => {
        // 发送添加请求
        await addSpecGroup({ categoryId: 0, name: value }).then(resp => {
          // 判断响应结果
          if (resp.data.code === 20000) {
            // 响应成功
            // 刷新页面
            this.getAllSpecGroup()
            // 提示成功信息
            Message({
              type: 'success',
              message: resp.data.message
            })
          } else {
            // 提示错误信息
            Message({
              type: 'warning',
              message: resp.data.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消添加'
        })
      })
      this.isAdding = false
    },

    // 根据id删除参数组
    async deleteSpecGroup (row) {
      this.isDeleting = true
      await deleteSpecGroupById(row.id).then(resp => {
        if (resp.data.code === 20000) {
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      // 移除规格组
      this.specGroupList.splice(this.specGroupList.indexOf(row), 1)
      this.isDeleting = false
    },

    // 获取顶级规格参数组
    async getAllSpecGroup () {
      this.isSearching = true
      await getSpecGroup(this.page, this.size, { categoryId: 0 }).then(resp => {
        if (resp.data.code === 20000) {
          this.specGroupList = resp.data.data.records
          this.total = resp.data.data.total
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      this.isSearching = false
    },


    // ----------------------------------------------------规格参数标签----------------------------------------------------

    // 删除规格参数标签
    async handleClose (param, groupParam) {
      this.isDeleting = true
      await deleteSpecParamById(param.id).then(resp => {
        if (resp.data.code === 20000) {
          // 提示成功
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      // 删除标签
      groupParam.splice(groupParam.indexOf(param), 1)
      this.isDeleting = false
    },

    // 添加规格参数标签
    async addTag (row) {
      // 表单验证
      // validate 方法是异步的
      this.$refs.addTagForm.validate(async valid => {
        // 如果表单验证失败
        if (!valid) {
          return false
        }
        // 提交表单 开启loading
        this.isAdding = true
        // 刷新一下这一行
        var t = this.expands
        // 填写归属规格组名
        this.tagForm.groupName = row.name
        await addSpecParam(this.tagForm).then(resp => {
          if (resp.data.code === 20000) {
            // 增加一个标签
            row.groupParam.push(resp.data.data)
            // 刷新一下这一行
            this.expands = []
            console.log('row' + JSON.stringify(row))
            // 提示成功
            Message({
              type: 'success',
              message: resp.data.message
            })
          } else {
            Message({
              type: 'warning',
              message: resp.data.message
            })
          }
        }).catch(() => {})
        // 刷新一下这一行
        this.expands = t
        // 关闭弹窗
        this.closeForm()
      })
    },


    // 根据id更新标签
    async updateTag (groupParam) {
      // 表单验证
      // validate 方法是异步的
      this.$refs.updateTagForm.validate(async valid => {
        // 如果表单验证失败，停止请求提交
        if (!valid) {
          return
        }
        // 提交表单 开启loading
        this.isAdding = true
        await updateSpecParamById(this.newParam).then(resp => {
          if (resp.data.code === 20000) {
            // 先移除
            groupParam.splice(groupParam.indexOf(this.oldParam), 1)
            // 再添加
            groupParam.push(resp.data.data)
            Message({
              type: 'success',
              message: resp.data.message
            })
          } else {
            Message({
              type: 'warning',
              message: resp.data.message
            })
          }
        }).catch(() => {})
        // 关闭弹窗
        this.closeForm()
      })
    },

    // 点击规格参数标签展示标签
    showTag (param) {
      // 打开弹窗
      this.isShowTag = true
      // 保存当前选中数据
      this.oldParam = param
      this.newParam.name = param.name
      this.newParam.id = param.id
      this.newParam.categoryId = param.categoryId
      this.newParam.options = param.options
      this.newParam.unit = param.unit
      this.newParam.groupName = param.groupName
      this.newParam.isGeneral = param.isGeneral
      this.newParam.isAggregation = param.isAggregation
      this.newParam.isSku = param.isSku
      this.newParam.type = param.type
    },


    // 关闭规格参数标签弹窗
    closeForm () {
      // 关闭弹窗
      this.isShowTag = false
      this.isAddTag = false
      // 清空数据
      this.tagForm.name = ''
      this.tagForm.unit = ''
      this.tagForm.categoryId = 0
      this.tagForm.options = ''
      this.tagForm.groupName = ''
      this.tagForm.isGeneral = ''
      this.tagForm.isAggregation = ''
      this.tagForm.isSku = ''
      this.tagForm.type = ''
      // 清空表单验证信息
      if (this.$refs.addTagForm !== undefined) {
        this.$refs.addTagForm.resetFields()
      }
      if (this.$refs.updateTagForm !== undefined) {
        this.$refs.updateTagForm.resetFields()
      }
      // 清空选中行
      this.tag = {}
      // 关闭loading
      this.isAdding = false
    },


    // -----------------------------------------其他----------------------------------------------

    // 单击某行时展开
    openColumn (row) {
      // 判断是否是点击同一行
      if (this.expands.length !== 0 && this.expands[0] === row.id) {
        // 重复点击同一行，目的是收起这一行
        this.expands = []
      } else {
        // 点击其他行，展开其他行，关闭这一行
        // 先初始化
        this.expands = []
        // 再添加
        this.expands.push(row.id)
      }
    },


    // 展开行变化时触发
    expandSelect (row, expandedRows) {
      var that = this
      // 只展开一行
      if (expandedRows.length) { // 说明展开了
        that.expands = []
        if (row) {
          that.expands.push(row.id) // 只展开当前行id
        }
      } else { // 说明收起了
        that.expands = []
      }
    },


    // 页码改变触发
    pageChange () {
      this.getAllSpecGroup()
    }

  }
}
</script>

<style scoped lang="less">
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .button-new-tag[data-v-f25321e2] {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
    margin-top: 5px;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    margin-top: 5px;
    vertical-align: bottom;
  }
  .el-tag + .el-tag[data-v-f25321e2] {
    margin-left: 10px;
    margin-top: 5px;
  }
  .add {
    height: 35px;
    display: flex;
    justify-content: space-between;
  }
  input {
    width: 350px;
    height: 35px;
    border-radius: 5px;
    padding-left: 10px;
    border: 1px solid #99a9bf;
  }
</style>
